from flask import Flask, render_template, request
from flask_socketio import SocketIO, emit

app = Flask(__name__)
socketio = SocketIO(app)

players = {}
choices = {}

# 主页
@app.route('/')
def index():
    return render_template('index.html')

# 玩家连接
@socketio.on('connect')
def on_connect():
    pass

# 接收玩家的昵称
@socketio.on('player_nickname')
def handle_nickname(data):
    player_id = request.sid
    nickname = data['nickname']
    ip_address = request.remote_addr

    # 保存玩家信息
    players[player_id] = {
        'nickname': nickname,
        'ip': ip_address
    }

    # 发送玩家信息给客户端
    emit('player_info', {'nickname': nickname, 'ip': ip_address})

# 玩家选择石头、剪刀、布
@socketio.on('player_choice')
def handle_choice(data):
    player_id = request.sid
    choice = data['choice']

    # 记录玩家选择
    choices[player_id] = choice

    # 检查两位玩家是否都做出选择
    emit('choice_update', {
        'nickname': players[player_id]['nickname'],
        'has_chosen': True
    }, broadcast=True)

    if len(choices) == 2:
        player_ids = list(choices.keys())
        choice_1 = choices[player_ids[0]]
        choice_2 = choices[player_ids[1]]

        # 获取玩家昵称
        nickname_1 = players[player_ids[0]]['nickname']
        nickname_2 = players[player_ids[1]]['nickname']

        # 计算结果
        result = determine_winner(choice_1, choice_2, nickname_1, nickname_2)

        # 发送结果给两位玩家
        emit('game_result', {
            'result': result,
            'choices': {
                nickname_1: choice_1,
                nickname_2: choice_2
            }
        }, broadcast=True)

        # 清空选择
        choices.clear()

# 判断结果
def determine_winner(choice_1, choice_2, nickname_1, nickname_2):
    if choice_1 == choice_2:
        return '平局！'
    elif (choice_1 == 'rock' and choice_2 == 'scissors') or \
         (choice_1 == 'scissors' and choice_2 == 'paper') or \
         (choice_1 == 'paper' and choice_2 == 'rock'):
        return f'{nickname_1} 获胜！'
    else:
        return f'{nickname_2} 获胜！'

if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', port=5000)
